﻿// //   Copyright 2007-2011 Comdiv (F. Sadykov) - http://code.google.com/u/fagim.sadykov/
// //   Supported by Media Technology LTD 
// //    
// //   Licensed under the Apache License, Version 2.0 (the "License");
// //   you may not use this file except in compliance with the License.
// //   You may obtain a copy of the License at
// //    
// //        http://www.apache.org/licenses/LICENSE-2.0
// //    
// //   Unless required by applicable law or agreed to in writing, software
// //   distributed under the License is distributed on an "AS IS" BASIS,
// //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// //   See the License for the specific language governing permissions and
// //   limitations under the License.
// //   
// //   MODIFICATIONS HAVE BEEN MADE TO THIS FILE

using System;
using System.Xml.Linq;
using Comdiv.QWeb.Files;
using Comdiv.QWeb.Serialization;

namespace Comdiv.QWeb.Logging {
	public class DefaultApplicationErrorLogger : ILogListener, IRegistryBound {
		private QWebServiceRegistry _registry;

		public DefaultApplicationErrorLogger() {
			FileName = "~/tmp/qweb.error.log.xml";
		}

		public string FileName { get; set; }
		public IFileNameResolver FileNameResolver { get; set; }

		#region ILogListener Members

		public void debug(object item, QWebContext context) {
		}

		public void trace(object item, QWebContext context) {
		}

		public void info(object item, QWebContext context) {
		}

		public void warn(object item, QWebContext context) {
			write(LogLevel.Warning, context, item);
		}

		public void error(object item, QWebContext context) {
			write(LogLevel.Error, context, item);
		}

		public void fatal(object item, QWebContext context) {
			write(LogLevel.Fatal, context, item);
		}

		public LogLevel Level { get; set; }

		#endregion

		#region IRegistryBound Members

		public void SetRegistry(QWebServiceRegistry registry) {
			_registry = registry;
			FileNameResolver = registry.FileNameResolver;
		}

		public QWebServiceRegistry Registry {
			get { return _registry; }
		}

		#endregion

		private void write(LogLevel level, QWebContext context, object item) {
			if (level < Level) return;
			var x = new XElement(level.ToString()
			                     , new XAttribute("time", DateTime.Now)
			                     , new XAttribute("app", context.Uri.Authority)
				);

			x.Add(null != _registry
			      	? new XAttribute("usr", _registry.PrincipalSource.CurrentUser.Identity.Name)
			      	: new XAttribute("usr", Environment.UserName));
			var ctx = XElement.Parse(new XmlSerializer().serialize("Context", context));
			var err = XElement.Parse(new XmlSerializer().serialize("error", item));
			x.Add(ctx, err);
			FileNameResolver.Write(FileName, x, context, append: true);
		}
	}
}